<template>
  <div class="execution">
    <div v-if="editDis">
      <dynamic-crud
        :rowAdd="rowadd"
        :data="tableData"
        :option="tableOptionEdit"
        :spanMethod="rowCount"
        :addDisabled="tableData.length > 0"
      >
        <avue-input-number
          slot="realAmount"
          :precision="2"
          :step="0"
          slot-scope="{ row, size }"
          v-model="row.realAmount"
          :disabled="!validatenull(row.unloadCase) && row.unloadCase != '3'"
          :size="size"
        ></avue-input-number>
        <avue-input-number
          slot="nsAmount"
          :precision="2"
          :step="0"
          slot-scope="{ row, size }"
          v-model="row.nsAmount"
          :disabled="!validatenull(row.unloadCase) && row.unloadCase != '3'"
          :size="size"
        ></avue-input-number>
      </dynamic-crud>
      <!-- <avue-form
        v-model="form.swStTvmCheckDetail"
        :option="formOptionEdit"
        style="margin-top: 40px"
      ></avue-form> -->
      <div class="bottom-menu">
        <!-- <el-button type="primary" :disabled="btn" @click="submit"
          >清点人确认</el-button
        > -->
        <el-button type="primary" :disabled="btn" @click="edit">保存</el-button>
        <el-button type="primary" @click="closeDia()">取消</el-button>
      </div>
    </div>
    <div v-if="viewDis">
      <avue-crud
        :data="tableData"
        :option="tableOptionView"
        :spanMethod="rowCount"
      ></avue-crud>
      <!-- <avue-form
        v-model="form.swStTvmCheckDetail"
        :option="formOptionView"
        style="margin-top: 40px"
      ></avue-form> -->
      <div class="bottom-menu">
        <el-button type="primary" @click="closeDialog()">取消</el-button>
      </div>
    </div>
    <div v-if="recordsDis">
      <avue-crud
        :data="tableDataRecords"
        :option="tableOptionRecords"
      ></avue-crud>
      <div class="bottom-menu">
        <el-button @click="closeDialog()">关闭</el-button>
      </div>
    </div>
    <div v-if="addDis">
      <dynamic-crud
        :data="tableData"
        :option="tableOption"
        :spanMethod="rowCount"
        :rowAdd="rowAdd1"
        :isShow="oneShow"
        :rowOneButton="oneButton"
        :addNew="rowNew"
      >
        <avue-input-number
          slot="realAmount"
          :precision="2"
          :step="0"
          slot-scope="{ row, size }"
          v-model="row.realAmount"
          :disabled="!validatenull(row.unloadCase) && row.unloadCase != '3'"
          :size="size"
        ></avue-input-number>
        <avue-input-number
          slot="nsAmount"
          :precision="2"
          :step="0"
          slot-scope="{ row, size }"
          v-model="row.nsAmount"
          :disabled="!validatenull(row.unloadCase) && row.unloadCase != '3'"
          :size="size"
        ></avue-input-number>
      </dynamic-crud>
      <!-- <avue-form
        v-model="form.swStTvmCheckDetail"
        :option="formOption"
        style="margin-top: 40px"
      ></avue-form> -->
      <div class="bottom-menu">
        <!-- <el-button type="primary" :disabled="btn" @click="submit"
          >清点人确认</el-button
        > -->
        <el-button type="primary" :disabled="btn" @click="save">保存</el-button>
        <el-button type="primary" @click="closeDia()">取消</el-button>
      </div>
    </div>
    <div>
      <el-dialog
        width="30%"
        title="清点人密码"
        :visible="dialogFormVisible"
        append-to-body
        center
        :destroy-on-close="true"
      >
        <el-form :model="form1">
          <el-form-item label="清点人密码" prop="password">
            <el-input
              v-model="form1.password"
              type="password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmUser">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  addObj,
  getTvmCode
} from "@/api/subwaystm/swsttvmcheck/swsttvmcheckdetail";
import {
  tableOption,
  tableOptionEdit,
  tableOptionView,
  tableOptionRecords
} from "@/const/crud/subwaystm/swsttvmcheck/swsttvmcheckdetailpaper";
import store from "@/store";
import { checkPwd } from "@/api/admin/user";
import { dateFormat } from "@/util/date";
import {validatenull} from "@/util/validate";
export default {
  name: "swsttvmcheckdetailpaper",
  inject: ["closeDialog"],
  data() {
    return {
      oneShow: true,
      rowNew: true,
      tvmList: [],
      tableData: [],
      tableDataRecords: [],
      tableOption: tableOption,
      tableOptionEdit: tableOptionEdit,
      tableOptionView: tableOptionView,
      tableOptionRecords: tableOptionRecords,
      dialogFormVisible: false,
      saveFlag: false,
      btn: false,
      form1: {
        password: ""
      },
      formOption: {
        submitBtn: false,
        emptyBtn: false,
        arrow: false,
        labelWidth: 120,
        column: [
          {
            type: "select",
            label: "清点人2",
            prop: "checkPersonTwoName",
            component: "user-select",
            params: {
              userCodeKey: "checkPersonTwoJopNo"
            },
            rules: [
              {
                required: true,
                message: "请选择清点人2！",
                trigger: "blur"
              }
            ]
          },
          {
            type: "input",
            label: "清点人2工号",
            prop: "checkPersonTwoJopNo",
            disabled: true
          },
          {
            type: "datetime",
            label: "清点时间",
            prop: "checkTime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            rules: [
              {
                required: true,
                message: "请选择清点时间！",
                trigger: "blur"
              }
            ]
          },
          {
            type: "date",
            label: "收益时间",
            prop: "revenueTime",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            display: false
          },
          {
            type: "textarea",
            label: "备注",
            prop: "remark",
            span: 24
          }
        ]
      },
      formOptionEdit: {
        submitBtn: false,
        emptyBtn: false,
        arrow: false,
        labelWidth: 120,
        column: [
          {
            type: "select",
            label: "清点人2",
            prop: "checkPersonTwoName",
            component: "user-select",
            params: {
              userCodeKey: "checkPersonTwoJopNo"
            },
            disabled: true
          },
          {
            type: "input",
            label: "清点人2工号",
            prop: "checkPersonTwoJopNo",
            disabled: true
          },
          {
            type: "datetime",
            label: "清点时间",
            prop: "checkTime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          },
          {
            type: "date",
            label: "收益时间",
            prop: "revenueTime",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            display: false
          },
          {
            type: "textarea",
            label: "备注",
            prop: "remark",
            span: 24
          }
        ]
      },
      formOptionView: {
        submitBtn: false,
        emptyBtn: false,
        detail: true,
        arrow: false,
        labelWidth: 120,
        column: [
          {
            type: "select",
            label: "清点人2",
            prop: "checkPersonTwoName",
            disabled: true
          },
          {
            type: "input",
            label: "清点人2工号",
            prop: "checkPersonTwoJopNo",
            disabled: true
          },
          {
            type: "datetime",
            label: "清点时间",
            prop: "checkTime",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss"
          },
          {
            type: "date",
            label: "收益时间",
            prop: "revenueTime",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            display: false
          },
          {
            type: "textarea",
            label: "备注",
            prop: "remark",
            span: 24
          }
        ]
      },
      form: {
        swStTvmCheckDetail: {},
        swStTvmCheckDetailPapers: []
      },
      isSubmit: false
    };
  },
  watch: {
    thisData() {
      this.tableData = this.thisData;
    },
    thisDataRecords(){
      this.tableDataRecords = this.thisDataRecords;
    },
    ThisMain() {
      this.form.swStTvmCheckDetail = this.ThisMain;
    },
    revenue: {
      handler() {
        this.form.swStTvmCheckDetail.revenueTime = this.revenue;
      },
      immediate: true
    },
    details: {
      handler() {
        this.form.swStTvmCheckDetail = this.details;
      },
      deep: true,
      immediate: true
    }
  },
  props: {
    thisData: {
      type: Array,
      default: function() {
        return [];
      }
    },
    ThisMain: Object,
    revenue: String,
    details: Object,
    viewDis: Boolean,
    editDis: Boolean,
    addDis: Boolean,
    mainId: Number,
    tvmCode: String,
    recordsDis: Boolean,
    thisDataRecords: {
      type: Array,
      default: function() {
        return [];
      }
    }
  },
  computed: {},
  mounted() {
    let now = new Date();
    if (now.getHours() < 6) {
      this.form.swStTvmCheckDetail.checkTime =
        dateFormat(now).substr(0, 10) + " 01:59:59";
    } else {
      this.form.swStTvmCheckDetail.checkTime = dateFormat(now);
    }
  },
  beforeMount() {
    getTvmCode().then(res => {
      this.tvmList = res.data.data.records;
    });
  },
  methods: {
    rowadd: function(callback) {
      if (this.editDis) {
        callback({
          tvmCode: this.form.swStTvmCheckDetail.tvmCode,
          unloadCase: "3"
        });
      } else {
        callback();
      }
    },
    rowAdd1: function(callback) {
      this.oneShow = false;
      this.tableOption.column[2].cell = true;
      callback({
        tvmCode: this.tvmCode,
        unloadCase: "3"
      });
    },
    delEditRow() {
      this.tableData.forEach(row => {
        let index = this.tableData.indexOf(row);
        this.tableData.splice(index, this.tableData.length);
      });
    },
    oneButton: function(callback) {
      this.rowNew = false;
      this.tableOption.column[2].cell = false;
      if (this.tableData.length > 0) {
        this.$confirm("此操作将重新生成, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.delEditRow();
          for (const item of this.tvmList) {
            const obj = Object.assign({}, item);
            obj.unloadCase = "3";
            callback(obj);
          }
          // for (const item of this.tableData) {
          //   Object.keys(item).map(key => {
          //     if (key != "$cellEdit" && key != "tvmCode") {
          //       item[key] = undefined;
          //     }
          //   });
          // }
        });
      } else {
        for (const item of this.tvmList) {
          const obj = Object.assign({}, item);
          obj.unloadCase = "3";
          callback(obj);
        }
      }
    },
    save: function() {
      this.form.swStTvmCheckDetail = this.details;
      if (
        this.validatenull(this.form.swStTvmCheckDetail.checkTime) ||
        this.validatenull(this.form.swStTvmCheckDetail.revenueTime) ||
        this.validatenull(this.form.swStTvmCheckDetail.checkPersonTwoName)
      ) {
        this.$message.info("清点时间、收益时间、清点人2为必填项！不能为空");
        return;
      }
      if (this.tableData.length == 0) {
        this.$message.info("请添加纸币回收箱信息！");
        return;
      } else {
        for (const item of this.tableData) {
          if (item.tvmCode == null) {
            this.$message.info("TVM编号为必填项！不能为空");
            return;
          }
          if (item.realAmount !== undefined) {
            if (String(item.realAmount).length > 5) {
              this.$message.info("请检查实点金额金额不能超过5位数！");
              return;
            }
          }
          if (item.nsAmount !== undefined) {
            if (String(item.nsAmount).length > 5) {
              this.$message.info("请检查非标准币金额不能超过5位数！");
              return;
            }
          }
        }
      }
      // if (!this.saveFlag) {
      //   this.$message.error("请先点击清点人确认按钮进行确认！");
      // } else {
      this.form.swStTvmCheckDetailPapers = this.tableData;
      this.form.swStTvmCheckDetail.checkPersonOneName =
        store.getters.userInfo.nikename;
      this.form.swStTvmCheckDetail.checkPersonOneJopNo =
        store.getters.userInfo.userCode;
      this.form.swStTvmCheckDetail.id = this.mainId;
      let now = new Date();
      if (now.getHours() < 6) {
        now.setDate(now.getDate() - 1);
      }
      if(this.form.swStTvmCheckDetail.revenueTime != dateFormat(now).substring(0, 10)){
        this.$confirm("收益时间不是系统默认时间,是否保存？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          addObj(this.form, 1)
            .then(res => {
              this.$message.success("添加成功");
              this.btn = true;
              this.saveFlag = false;
              this.$emit("update:mainId", res.data.data);
              done();
              //this.getList(this.page);
            })
            .catch(() => {
              loading();
            });
        })
      } else {
        addObj(this.form, 1)
          .then(res => {
            this.$message.success("添加成功");
            this.btn = true;
            this.saveFlag = false;
            this.$emit("update:mainId", res.data.data);
            done();
            //this.getList(this.page);
          })
          .catch(() => {
            loading();
          });
      }
      //}
    },
    edit: function() {
      if (
        this.validatenull(this.form.swStTvmCheckDetail.checkTime) ||
        this.validatenull(this.form.swStTvmCheckDetail.revenueTime) ||
        this.validatenull(this.form.swStTvmCheckDetail.checkPersonTwoName)
      ) {
        this.$message.info("清点时间、收益时间、清点人2为必填项！不能为空");
        return;
      }
      if (this.tableData.length == 0) {
        this.$message.info("请添加纸币回收箱信息！");
        return;
      } else {
        for (const item of this.tableData) {
          if (item.tvmCode == null) {
            this.$message.info("TVM编号为必填项！不能为空");
            return;
          }
          if (item.realAmount !== undefined) {
            if (String(item.realAmount).length > 5) {
              this.$message.info("请检查实点金额金额不能超过5位数！");
              return;
            }
          }
          if (item.nsAmount !== undefined) {
            if (String(item.nsAmount).length > 5) {
              this.$message.info("请检查非标准币金额不能超过5位数！");
              return;
            }
          }
        }
      }
      // if (!this.saveFlag) {
      //   this.$message.error("请先点击清点人确认按钮进行确认！");
      // } else {
      this.form.swStTvmCheckDetailPapers = this.tableData;
      // this.form.swStTvmCheckDetail.checkPersonOneName =
      //   store.getters.userInfo.nikename;
      // this.form.swStTvmCheckDetail.checkPersonOneJopNo =
      //   store.getters.userInfo.userCode;
      // this.form.swStTvmCheckDetail.id = this.mainId;
      addObj(this.form, 2)
        .then(res => {
          this.$message.success("修改成功");
          this.btn = true;
          this.saveFlag = false;
          this.$emit("update:mainId", res.data.data);
          done();
          //this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
      //}
    },
    closeDia() {
      this.$confirm("请确认是否已将所有产生数据的钱箱界面点击保存", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.closeDialog();
      });
      this.btn = false;
    },
    submit() {
      this.form1 = {};
      if (this.form.swStTvmCheckDetail.checkPersonTwoJopNo == "") {
        this.$message.error("请选择清点人！");
        return;
      }
      this.$prompt("请输入清点人2密码", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: val => {
          if (!val) return "请输入密码";
        }
      })
        .then(({ value }) => {
          return checkPwd(
            this.form.swStTvmCheckDetail.checkPersonTwoJopNo,
            value
          );
        })
        .then(response => {
          var result = response.data.data;
          if (result) {
            this.$message.success("确认成功");
            this.saveFlag = true;
            return;
          } else {
            this.$message.error("密码错误");
            return Promise.reject("密码错误");
          }
        })
        .catch(error => {
          console.log(error);
          this.isSubmit = false;
        });
    },
    confirmUser: function() {
      if (this.form.swStTvmCheckDetail.checkPersonTwoJopNo == "") {
        this.$message.error("请选择清点人！");
      } else if (this.form1.password.length == 0) {
        this.$message.error("请输入清点人密码!");
      } else {
        checkPwd(
          this.form.swStTvmCheckDetail.checkPersonTwoJopNo,
          this.form1.password
        ).then(response => {
          let data = response.data.data;
          if (data) {
            this.$message.success("输入正确");
            this.dialogFormVisible = false;
            this.saveFlag = true;
          } else {
            this.$message.error("用户名或密码不正确！");
          }
        });
      }
    },
    rowCount: function({ row, column, rowIndex, columnIndex }) {
      // if (row.sysAmount == null) {
      //   return false;
      // }
      if (row.realAmount == null) {
        return false;
      }
      if (row.nsAmount == null) {
        return false;
      }

      // row.diffAmount =
      //   row.sysAmount - (Number(row.realAmount) + Number(row.nsAmount)) + "";
      if (!this.validatenull(row.unloadCase) && row.unloadCase != "3") {
        row.realAmount = undefined;
        row.nsAmount = undefined;
        row.diffAmount = undefined;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.bottom-menu {
  text-align: center;
}
</style>
